#!/usr/bin/env node

import { readFileSync, existsSync } from 'fs'
import { join } from 'path'

const COVERAGE_FILE = 'coverage/coverage-summary.json'
const THRESHOLDS = {
  statements: 80,
  branches: 80,
  functions: 80,
  lines: 80
}

console.log('🔍 Checking test coverage...\n')

if (!existsSync(COVERAGE_FILE)) {
  console.error('❌ Coverage file not found. Run tests with coverage first.')
  console.error('   pnpm test:coverage')
  process.exit(1)
}

try {
  const coverage = JSON.parse(readFileSync(COVERAGE_FILE, 'utf8'))
  const total = coverage.total
  
  console.log('📊 Coverage Report:')
  console.log('─'.repeat(50))
  
  let allPassed = true
  
  for (const [metric, threshold] of Object.entries(THRESHOLDS)) {
    const actual = total[metric].pct
    const passed = actual >= threshold
    const status = passed ? '✅' : '❌'
    
    console.log(`${status} ${metric.padEnd(12)}: ${actual.toFixed(2)}% (threshold: ${threshold}%)`)
    
    if (!passed) {
      allPassed = false
    }
  }
  
  console.log('─'.repeat(50))
  
  if (allPassed) {
    console.log('🎉 All coverage thresholds met!')
    process.exit(0)
  } else {
    console.log('⚠️  Some coverage thresholds not met.')
    console.log('   Consider adding more tests to improve coverage.')
    process.exit(1)
  }
  
} catch (error) {
  console.error('❌ Error reading coverage file:', error.message)
  process.exit(1)
}